package com.keeplearning;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DictionaryReplacer {

    private static Pattern PATTERN = Pattern.compile("\\$(\\w+)\\$");

    public static String replace(String s, Map<String, String> dict) {

        Matcher matcher = PATTERN.matcher(s);

        StringBuffer buf = new StringBuffer();

        while (matcher.find()) {

            String var = matcher.group(1);
            //System.out.println(var);
            if (dict.containsKey(var)) {
                matcher.appendReplacement(buf, dict.get(var));
            } else {
                buf.append("");
            }
        }
        matcher.appendTail(buf);
        return buf.toString();

    }



}
